package com.misty.api.service.Excel;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.misty.api.service.ExcelService;
import com.misty.common.bean.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @ClassName : ExcelServiceImpl
 * @Description :
 * @Author :
 * @Date: 2022-12-23 22:11
 */
@Service
@Slf4j
public class ExcelServiceImpl implements ExcelService {

     /**
      * @param
      * @return
      * @Description 下载excel
      * @Date 2022/12/24 22:01
      */
     @Override
    public void download(String fileType, List<?> data, HttpServletRequest request, HttpServletResponse response) {

        String fileName = this.getExcelFileName(fileType);

        String filePath = this.getExcelFilePath(fileName);

        try {
            boolean exist = this.judgeFileExist(filePath, response);
            if(!exist){
                return ;
            }

            this.exportExcelInfo(filePath,fileName,data,response);

        } catch (IOException e) {
            e.printStackTrace();
            log.debug("导出文件失败");
        }

    }

     /**
      * @param
      * @return
      * @Description 下载excel模板
      * @Date 2022/12/24 22:03
      */
     @Override
    public void downloadTemplate(String fileType,
                                 HttpServletRequest request, HttpServletResponse response) {

        String fileName = this.getExcelTemplateFileName(fileType);

        String filePath = this.getExcelFilePath(fileName);

        try (
                ServletOutputStream out = response.getOutputStream();//读取文件流
        ){

            boolean exist = this.judgeFileExist(filePath, response);
            if(!exist){
                return ;
            }

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //为文件重新设置名字，采用数据库内存储的文件名称
            response.setHeader("Content-disposition", "attachment; filename="
                    + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));

            byte[] bytes = FileUtil.readBytes(filePath);
            // 通过文件的路径读取文件字节流
            out.write(bytes);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param
     * @return
     * @Description  导出全部数据的excel
     * @Date 2022/12/14 21:13
     */
    @Override
    public void exportExcelInfo(String filePath, String fileName, List<?> data, HttpServletResponse response) throws IOException {

        log.info("================= 开始导出excel ==================");
        response.reset();
        try (

                OutputStream out = response.getOutputStream();
                BufferedOutputStream bos = new BufferedOutputStream(out);
        ){

            //设置文件返回类型 与 请求头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = formatter.format(date);
            String fileNameStr = fileName.split("\\.")[0] + "_" + dateStr + "." + fileName.split("\\.")[1];

            String outFileName = URLEncoder.encode(fileNameStr, "utf-8");
            response.setHeader("Content-disposition", "attachment; filename="
                    + new String(fileNameStr.getBytes("utf-8"), "ISO-8859-1"));

            //读取Excel
            ExcelWriter excelWriter = EasyExcel.write(bos).withTemplate(filePath).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();

            //list map 是查询并需导出的数据，并且里面的字段和excel需要导出的字段对应
            // 直接写入Excel数据
//            Map<String,Object> map = yyy;
//            excelWriter.fill(map, writeSheet);
//            List<Map> list = xxx;

            excelWriter.fill(data, writeSheet);
            excelWriter.finish();
            bos.flush();

        } catch (Exception e) {
            e.printStackTrace();
            return;
        } finally {
            log.info("================= 导出excel结束 ==================");
//            response.reset();
        }
    }

    /**
     * @param
     * @return
     * @Description 获取导出excel模板文件名
     * @Date 2022/12/14 21:15
     */
    @Override
    public String getExcelFileName(String fileType){
        String fileName = "";
        switch (fileType){
            case "blog":
                fileName = "博客.xls";
                break;
            default:
                fileName = "未知.xls";
                break;
        }
        return  fileName;
    }


    /**
     * @param
     * @return
     * @Description 获取导出excel模板文件名
     * @Date 2022/12/14 21:15
     */
    @Override
    public String getExcelTemplateFileName(String fileType){
        String fileName = "";
        switch (fileType){
            case "blog":
                fileName = "博客（模板）.xls";
                break;
            default:
                fileName = "未知.xls";
                break;
        }
        return  fileName;
    }


    /**
     * @param
     * @return
     * @Description 获取文件路径
     * @Date 2022/12/14 21:20
     */
    @Override
    public String getExcelFilePath(String fileName) {
        String pathName = System.getProperty("user.dir");
        String path = "file" + File.separator + "excelTemplate" + File.separator;
        String filePath = pathName + File.separator + path + fileName;

        log.info("=============获取文件路径 {}================",filePath);
        return filePath;
    }


    @Override
    public boolean judgeFileExist(String filePath, HttpServletResponse response) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            String res = JSONUtil.toJsonStr(Result.error("文件不存在"));
            log.info(res);
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return false;
        }
        return true;
    }
}
